<template>
  <el-tab-pane label="账号管理" name="accoutManage">
    <!-- ========================================= -->
    <el-table :data="data.user_list" style="width: 100%" :show-overflow-tooltip="true">
      <el-table-column fixed sortable prop="name" label="用户名"></el-table-column>
      <el-table-column sortable prop="desc_info" label="备注信息" width="200"></el-table-column>
      <el-table-column sortable prop="is_admin" label="是否管理员"></el-table-column>
      <el-table-column sortable prop="is_enable" label="是否启用"></el-table-column>
      <!-- <el-table-column sortable prop="created_at" label="创建时间" width="180"></el-table-column> -->
      <el-table-column sortable prop="expiry_at" label="过期时间" width="180"></el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #header>
          <el-button size="small" type="primary" @click="addUser">新增</el-button>
          <el-button size="small" type="primary" @click="getUserList(0, 10000)">刷新</el-button>
        </template>
        <template #default="scope">
          <el-button size="small" type="success" @click="editUser(scope.row)">编辑</el-button>
          <el-popconfirm confirmButtonText="删除" cancelButtonText="取消" icon="el-icon-info" iconColor="red" title="确定删除吗"
            @confirm="deleteUserById(scope.row.id)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>
    <!-- ========================================= -->
    <el-dialog title="用户信息" v-model="data.user_dialog_visible" width="60%" class="user-dialog">
      <div class="user-form-container">
        <el-form label-width="100px" ref="user_form" :model="user" class="user-form">
          <div class="user-form-section">
            <h3 class="section-title">基础信息</h3>
            <div class="section-content">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="用户名" prop="name" required>
                    <el-input v-model.trim="user.name" minlength="1" maxlength="30" show-word-limit class="user-input"
                      placeholder="请输入用户名">
                      <template #prefix>
                        <el-icon>
                          <User />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="备注名" prop="desc_info">
                    <el-input v-model.trim="user.desc_info" minlength="1" maxlength="60" show-word-limit
                      class="user-input" placeholder="请输入备注">
                      <template #prefix>
                        <el-icon>
                          <Edit />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="密码" prop="pwd" required>
                    <el-input v-model.trim="user.pwd" type="password" show-password minlength="1" maxlength="60"
                      show-word-limit class="user-input" placeholder="请输入密码">
                      <template #prefix>
                        <el-icon>
                          <Lock />
                        </el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="过期时间" required>
                    <el-date-picker v-model="user.expiry_at" type="datetime" placeholder="选择账号过期时间"
                      class="user-date-picker" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="管理员" prop="is_admin">
                    <el-radio-group v-model="user.is_admin" class="user-radio-group">
                      <el-radio value="Y">是</el-radio>
                      <el-radio value="N">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="启用" prop="is_enable">
                    <el-radio-group v-model="user.is_enable" class="user-radio-group">
                      <el-radio value="Y">是</el-radio>
                      <el-radio value="N">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-form>
      </div>

      <template #footer>
        <div class="user-form-footer">
          <el-button @click="data.user_dialog_visible = false" size="large">取消</el-button>
          <el-button type="primary" @click="saveUser" size="large">
            <el-icon>
              <Check />
            </el-icon>保存
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- ========================================= -->
  </el-tab-pane>
</template>

<script setup lang="ts">

import { onMounted, reactive } from "vue";
import { type Router, useRoute, useRouter } from "vue-router";
import { ElMessage, ElPopover, ElNotification, ElMessageBox, dayjs } from "element-plus";
import axios from "axios";
import { User, Edit, Lock, Check } from '@element-plus/icons-vue';


enum Mode {
  "create" = 0,
  "update" = 1,
}

/**
 * 用户信息
 */

interface User {
  id: number;
  name: string;
  pwd: string;
  desc_info: string;
  is_admin: "Y" | "N";
  is_enable: "Y" | "N";
  is_root: "Y" | "N";
  expiry_at: Date;
}

interface UserInfo extends User {
  created_at?: string;
  updated_at?: string;
}

interface ResponseData {
  code: number;
  msg: string;
  data?: any
}

let data = reactive({
  mode: Mode.create,
  user_dialog_visible: false,
  active_name: "accoutManage",
  user_list: Array<UserInfo>(),
  is_admin: true,
});

let user = reactive<User>({
  id: 0,
  name: "",
  pwd: "",
  desc_info: "",
  is_admin: "N",
  is_enable: "Y",
  is_root: "N",
  expiry_at: new Date(2050, 0, 0, 0, 0, 0)
});


/**
 * 获取用户列表
 */
function getUserList(offset: number = 0, limit: number = 10000) {
  axios.get<ResponseData>(`/api/user?offset=${offset}&limit=${limit}`)
    .then((ret) => {
      if (ret.data.code === 0) {
        data.user_list = ret.data.data;
      } else {
        ElMessage.error("获取用户列表错误");
      }
    })
}

/**
 * 添加用户
 */
function addUser() {
  user.id = 0;
  user.name = "";
  user.pwd = "";
  user.desc_info = "";
  user.is_admin = "N";
  user.is_enable = "Y";
  user.is_root = "N";
  user.expiry_at = new Date(2050, 0, 0, 0, 0, 0);
  data.user_dialog_visible = true;

}

/**
 * 编辑用户
 * @param u 
 */
function editUser(u: UserInfo) {
  user.id = u.id;
  user.name = u.name;
  user.pwd = u.pwd;
  user.desc_info = u.desc_info;
  user.is_admin = u.is_admin;
  user.is_enable = u.is_enable;
  user.is_root = u.is_root;
  user.expiry_at = u.expiry_at;
  data.user_dialog_visible = true;
}


function getRequestBody(): any {
  return {
    id: user.id,
    name: user.name,
    pwd: user.pwd,
    desc_info: user.desc_info,
    is_admin: user.is_admin,
    is_enable: user.is_enable,
    is_root: user.is_root,
    expiry_at: dayjs(user.expiry_at).format("YYYY-MM-DD HH:mm:ss"),
  }
}

/**
 * 根据ID更新用户
 * @param userId ID
 */
function updateUserById() {
  axios.put<ResponseData>(`/api/user`, getRequestBody())
    .then((ret) => {
      if (ret.data.code === 0) {
        data.user_list = ret.data.data;
      } else {
        ElMessage.error("更新用户错误,请检查输入");
      }
    })
}

/**
 * 根据ID删除用户
 * @param userId ID
 */
function deleteUserById(userId: number) {
  axios.delete<ResponseData>(`/api/user/${userId}`)
    .then((ret) => {
      if (ret.data.code === 0) {
        data.user_list = ret.data.data;
      } else {
        ElMessage.error("删除用户错误");
      }
    })
}

/**
 * 创建用户
 */
function createUser() {
  axios.post<ResponseData>(`/api/user`, getRequestBody())
    .then((ret) => {
      if (ret.data.code === 0) {
        data.user_list = ret.data.data;
      } else {
        ElMessage.error("创建用户错误,请检查输入");
      }
    })
}

function saveUser() {
  if (user.id === 0) {
    createUser();
  } else {
    updateUserById()
  }
  user.id = 0;
  user.name = "";
  user.pwd = "";
  user.desc_info = "";
  user.is_admin = "N";
  user.is_enable = "Y";
  user.is_root = "N";
  user.expiry_at = new Date(2050, 0, 0, 0, 0, 0);
  data.user_dialog_visible = false;
}


onMounted(() => {
  getUserList();
})


</script>


<style scoped>
.user-dialog :deep(.el-dialog__header) {
  background: linear-gradient(45deg, #1976d2, #64b5f6);
  padding: 20px 25px;
  margin-right: 0;
}

.user-dialog :deep(.el-dialog__title) {
  color: #ffffff;
  font-weight: 500;
}

.user-form-container {
  padding: 0 15px;
  max-height: calc(90vh - 120px);
  overflow-y: auto;
}

.user-form-section {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 2px 12px 0 rgba(25, 118, 210, 0.08);
}

.section-title {
  color: #1976d2;
  font-size: 16px;
  font-weight: 500;
  padding: 12px 20px;
  margin: 0;
  border-bottom: 2px solid #e8f0fe;
}

.section-content {
  padding: 15px 20px;
}

.user-input :deep(.el-input__wrapper) {
  box-shadow: 0 2px 12px 0 rgba(25, 118, 210, 0.08);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.user-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 12px 0 rgba(25, 118, 210, 0.15);
}

.user-input :deep(.el-input__prefix-inner) {
  color: #1976d2;
  font-size: 16px;
}

.user-date-picker {
  width: 100%;
}

.user-date-picker :deep(.el-input__wrapper) {
  box-shadow: 0 2px 12px 0 rgba(25, 118, 210, 0.08);
  border-radius: 8px;
  transition: all 0.3s ease;
}

.user-date-picker :deep(.el-input__wrapper:hover) {
  box-shadow: 0 2px 12px 0 rgba(25, 118, 210, 0.15);
}

.user-radio-group {
  display: flex;
  gap: 20px;
}

.user-radio-group :deep(.el-radio__input.is-checked .el-radio__inner) {
  background: #1976d2;
  border-color: #1976d2;
}

.user-radio-group :deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #1976d2;
}

.user-form-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 10px 20px 20px;
  background: #fff;
  border-top: 1px solid #e8f0fe;
}

.user-form-footer .el-button {
  padding: 0 25px;
  height: 40px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-form-footer .el-button[type="primary"] {
  background: linear-gradient(45deg, #1976d2, #64b5f6);
  border: none;
  color: white;
}

.user-form-footer .el-button[type="primary"]:hover {
  background: linear-gradient(45deg, #1565c0, #42a5f5);
  transform: translateY(-2px);
  box-shadow: 0 4px 15px 0 rgba(25, 118, 210, 0.25);
}

@media (max-width: 768px) {
  .user-dialog {
    width: 95% !important;
    margin: 10px auto !important;
  }

  .section-content {
    padding: 10px;
  }

  .user-form-footer .el-button {
    padding: 0 15px;
  }
}
</style>